package cn.com.dhcc.turbo.service.sysmgr;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.BaseService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.YESNO;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.registry.AdapterInfo;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo.SL_AUTH_FLAG;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo.USER_TYPE;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfoExt;
import cn.com.dhcc.turbo.entity.sysmgr.wapper.UserInfoRowWapper;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

/**
 * 用户管理
 * 
 * @author qiao
 * @2013-11-20 @下午3:18:35
 */
@Service
public class UserMgrService extends BaseService {

	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(LOGTYPE.SYS);
	@Autowired
	NodeInfoService nodeInfoService;
	public UserInfo getUserInfoByUserName(String userName) throws ServiceException {
		WhereCondition searchParameter = new WhereCondition();
		searchParameter.where().eq("USER_NAME", userName);
		NodeInfo loaclNode = nodeInfoService.getLocalNode();
		try {
			UserInfo userInfo = CM.getDao().getModule("根据用户名获取用户", UserInfo.class, searchParameter);
			if (userInfo == null)
				return null;
			if (userInfo.isNodeUser()) {
				userInfo.setUserNameStr("节点管理员");
			} else if("2".equals(userInfo.getUserType())) {
				userInfo.setUserNameStr("节点用户");
			}else{
				String sql = "select ADAPTER_NAME  from " + SI_TABLE("turbo_adapter_info") + " where id=?";
				String sysName = CM.getDao().queryForString("获取当前登录用户的适配器名", sql, new Object[] { userInfo.getOwnId() });
				userInfo.setUserNameStr(sysName + "_管理员");
			}
			if(loaclNode != null){
				userInfo.setNodeName(loaclNode.getNodeName());
			}
			
			return userInfo;
		} catch (DaoException e) {
			throw new ServiceException("根据用户名获取用户失败", e);
		}
	}

	public List<UserInfo> getSysUserList(String id) throws ServiceException {
		String sql = " select t.*,s.sys_name userNameStr from " + SI_TABLE("TURBO_USER") + " t left join "
				+ SI_TABLE("turbo_sys_info")
				+ " s on t.own_id = s.id where t.user_name<>'admin' order by t.user_type desc,t.mtime desc";
		WhereCondition searchParameter = new WhereCondition();
		try {
			return CM.getDao().listModule("获取系统用户", sql, UserInfo.class, searchParameter);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public String resetPwdByUserId(String id) throws ServiceException {
		try {
			UserInfo userInfo = CM.getDao().getModuleById("获取系统用户", UserInfo.class, new Object[] { id });
			userInfo.setPwd(userInfo.getUserName());
			CM.getDao().updateModuleById("重置密码", userInfo, null);
			return userInfo.getUserName();
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public void insertOrUpdateUser(UserInfo user) throws ServiceException {
		try {
			CM.getDao().saveOrUpdateModuleByIdExecuteNull("添加或者修改用户信息", user);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

   public void createAdapterUser(AdapterInfo adapterInfo) throws ServiceException {
		try {
			UserInfo adapterUser = this.getUserByUserName(adapterInfo.getAdapterCode());
			if (adapterUser==null) {
				adapterUser = new UserInfo();
				adapterUser.setId(UUIDGenerator.getUUID());
				adapterUser.setMtime(new Date());
				adapterUser.setUserType(YESNO.NO.getStatus());
				adapterUser.setOwnId(adapterInfo.getId());
				adapterUser.setPwd(adapterInfo.getAdapterCode());
				adapterUser.setUserName(adapterInfo.getAdapterCode());
				//TODO by适配器对应用户eamil暂时为空
				adapterUser.setEmail(null);
				insertOrUpdateUser(adapterUser);
			}
		} catch (ServiceException e) {
			throw new ServiceException(e);
		}
	}

	public UserInfo getNodeAdminUser() throws ServiceException {
		try {
			return getUserInfoByUserName(NodeInfoParam.ADMIN_USERNAME);
		} catch (ServiceException e) {
			throw e;
		}
	}

	public void deleteAdapterUser(AdapterInfo adapterInfo) throws ServiceException {
		WhereCondition condition = WhereCondition.newInstance().where().eq("USER_NAME", adapterInfo.getAdapterCode());
		try {
			CM.getDao().deleteModule("删除登录用户", UserInfo.class, condition);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	/**
	 * 通过用户Id更改密码
	 * 
	 * @param id
	 * @param newPassword
	 * @throws ServiceException
	 */
	public void changePwdByUserId(String id, String newPassword) throws ServiceException {
		try {
			UserInfo userInfo = CM.getDao().getModuleById("获取系统用户", UserInfo.class, new Object[] { id });
			userInfo.setPwd(newPassword);
			CM.getDao().updateModuleById("重置密码", userInfo, null);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public void deleteUser(String id) throws ServiceException {
		WhereCondition condition = WhereCondition.newInstance().where().eq("id", id);
		try {
			CM.getDao().deleteModule("删除登录用户", UserInfo.class, condition);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public boolean isPropertyUnique(String property, String newValue, String oldValue) throws ServiceException {
		if (newValue == null || newValue.equals(oldValue)) {
			return false;
		}
		WhereCondition searchParameter = new WhereCondition();
		searchParameter.where().eq(property, newValue);
		try {
			UserInfo userInfo = CM.getDao().getModule("根据用户名获取用户", UserInfo.class, searchParameter);
			if (userInfo == null)
				return true;
		} catch (DaoException e) {
			throw new ServiceException("根据用户名获取用户失败", e);

		}
		return false;

	}

	public UserInfo get(String id) throws ServiceException {
		try {
			return CM.getDao().getModuleById("获取系统用户", UserInfo.class, new Object[] { id });
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public UserInfo getByuserNameAndEmail(String userName, String email) throws ServiceException {
		WhereCondition searchParameter = new WhereCondition();
		searchParameter.where().eq("user_name", userName);
		searchParameter.and().eq("email", email);
		UserInfo userInfo;
		try {
			userInfo = CM.getDao().getModule("根据用户名和邮箱获取用户", UserInfo.class, searchParameter);
		} catch (DaoException e) {
			throw new ServiceException("根据用户名获和邮箱取用户失败", e);
		}
		return userInfo;
	}

	public void addUserExt(UserInfoExt vo) throws ServiceException {
		try {
			CM.getDao().saveOrUpdateModuleByIdExecuteNull("添加或者修改用户扩展信息", vo);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}

	}

	public UserInfoExt getByuserExtByid(String id) throws ServiceException {
		try {
			return CM.getDao().getModuleById("获取系统用户", UserInfoExt.class, new Object[] { id });
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public void deleteUserExt(String id) throws ServiceException {
		WhereCondition condition = WhereCondition.newInstance().where().eq("id", id);
		try {
			CM.getDao().deleteModule("删除用户扩展信息", UserInfoExt.class, condition);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public PagerData<UserInfo> list(Pager pager, WhereCondition condition) throws ServiceException {
		String sql = " select t.*,s.adapter_name userNameStr from " + SI_TABLE("TURBO_USER") + " t left join "
				+ SI_TABLE("turbo_adapter_info") + " s on t.own_id = s.id";
		try {
			return CM.getDao().getPagerList("获取用户信息列表", sql, new UserInfoRowWapper(), pager, condition,
					new Object[] {});
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}
	/**
	 * 创建管理员用户
	 * @param email
	 * @throws ServiceException
	 * @throws NiceException
	 */
	public void createLocalAdminUser(String email) throws ServiceException{
		try {
			UserInfo nodeAdmin = getNodeAdminUser();
			if (nodeAdmin == null) {
				//创建节点初始化用户
				nodeAdmin = new UserInfo();
				nodeAdmin.setId(UUIDGenerator.getUUID());
				nodeAdmin.setMtime(new Date());
				nodeAdmin.setUserType(USER_TYPE.ADMINUSER.getCode());
				nodeAdmin.setPwd(NodeInfoParam.DEFAULT_ADMIN_PWD);
				nodeAdmin.setUserName(NodeInfoParam.ADMIN_USERNAME);
				nodeAdmin.setEmail(NodeInfoParam.MWR_NODE_ADMIN_EMAIL);
				insertOrUpdateUser(nodeAdmin);
			}
		} catch (ServiceException e1) {
			throw e1;
		} 
		
	}
	public UserInfo getUserByUserName(String userName) throws ServiceException{
		String sql = " select * from " + SI_TABLE("TURBO_USER") +" where user_name=?";
		try {
			return CM.getDao().get("获取系统用户", sql,new UserInfoRowWapper(), new Object[] { userName });
		} catch (DaoException e) {
			throw new ServiceException("获取系统用户失败");
		}
	}

	public String getUserAuthFlag(UserInfo userInfo) throws NiceException {
		String userType = userInfo.getUserType();
		if((USER_TYPE.ADMINUSER.getCode().equalsIgnoreCase(userType)
				||USER_TYPE.NODEUSER.getCode().equalsIgnoreCase(userType))
				&&NodeInfoParam.isMwr()
				&&NodeInfoParam.isManaagerNode()){
			return SL_AUTH_FLAG.MWR_NODE_ADMIN_USER.getCode();
		}else if((USER_TYPE.ADMINUSER.getCode().equalsIgnoreCase(userType)
				||USER_TYPE.NODEUSER.getCode().equalsIgnoreCase(userType))
				&&!NodeInfoParam.isMwr()
				&&NodeInfoParam.isManaagerNode()){
			return SL_AUTH_FLAG.NOT_MWR_MGR_NODE_ADMIN_USER.getCode();
		}else if((USER_TYPE.ADMINUSER.getCode().equalsIgnoreCase(userType)
				||USER_TYPE.NODEUSER.getCode().equalsIgnoreCase(userType))
				&&!NodeInfoParam.isManaagerNode()){
			return SL_AUTH_FLAG.NOT_MGR_NODE_ADMIN_USER.getCode();
		}else if(USER_TYPE.SYSUSER.getCode().equalsIgnoreCase(userType)){
			return SL_AUTH_FLAG.SYS_USER.getCode();
		}else{
			logger.error("用户信息加载错误，error user type");
			throw new NiceException("用户信息加载错误");
		}
	}
}
